package com.alinesno.cloud.compoment.generate.generator.tools;

import java.io.IOException;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.model.JobWithDetails;

/**
 * Jenkins 持续集成工具类
 * 
 * @author WeiXiaoJin
 * @since 2019年9月14日 下午8:28:54
 */
public class JenkinsTools {
	
	private static final Logger log = LoggerFactory.getLogger(JenkinsTools.class) ;
		// 初始化模板引擎
    private static VelocityEngine velocityEngine = new VelocityEngine();
        
    static {
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.init();
    }
	
	/**
	 * 创建job工程
	 * @param bean
	 * @return
	 * @throws IOException 
	 * @throws URISyntaxException 
	 */
	public static void buildJob(JenkinsJobBean bean , 
				String url , 
				String username , 
				String password , 
				String templatePath) throws IOException, URISyntaxException {
		
		log.debug("url:{} , username:{} , password:{}" , url , username , password);

        // 获取模板文件
        Template template = velocityEngine.getTemplate("templates/"+templatePath+".vm");

        // 设置变量，velocityContext是一个类似map的结构
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("bean", bean);
		
		JenkinsServer jenkins = new JenkinsServer(new URI(url), username, password);
		log.debug("jenkins:{}" , jenkins);
		
		StringWriter stringWriter = new StringWriter();
	    template.merge(velocityContext, stringWriter);
	    
	    System.out.println(bean.getJobName())  ; 
	    System.out.println(stringWriter.toString());
		
		JobWithDetails job = jenkins.getJob(bean.getJobName()) ; 
		if(job == null) {
			jenkins.createJob(bean.getJobName(), stringWriter.toString() , false);
		}else {
			jenkins.updateJob(bean.getJobName(), stringWriter.toString() , false);
		}
		jenkins.getJob(bean.getJobName()).build(); 
	}

	/**
	 * 创建maven配置
	 * @param bean
	 * @param url
	 * @param username
	 * @param password
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static void buildMavenJob(JenkinsJobBean bean , 
			String url , 
			String username , 
			String password) throws IOException, URISyntaxException {
		buildJob(bean, url, username, password, "jenkins.maven");
	}

}
